﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace N2.BlogEngine.Providers
{
	using BlogEngine;
	using global::BlogEngine.Core.Providers;
	using Items;
	using N2;
	using be = global::BlogEngine.Core;
	using n2 = N2.BlogEngine;
	
	partial class N2BlogProvider
	{
		public override be.Category SelectCategory(Guid id)
		{
			var _category = Context.Persister.Get<BeCategory>(id.ToInt());

			if (null == _category && this.UseFallBackProvider) {
				be.Category _innerCategory = FallBackProvider.SelectCategory(id);
				_innerCategory.Id = id;
				this.UpdateCategory(_innerCategory);

				return _innerCategory;
			}
			
			return _category.AsBlogEngine();
		}

		public override void InsertCategory(be.Category category)
		{
			this.UpdateCategory(category);
		}

		public override void UpdateCategory(be.Category category)
		{
			Context.Persister.Save(category.AsN2());
		}

		public override void DeleteCategory(be.Category category)
		{
			Context.Persister.Delete(category.AsN2());
		}

		List<be.Category> TryFillingCategories()
		{
			return n2.BlogService
				.CurrentBlog
				.Categories
				.ItemHierarchy
				.Select<BeCategory, be.Category>(ItemExtensions.AsBlogEngine)
				.ToList();
		}

		public override List<be.Category> FillCategories()
		{
			var _categories = this.TryFillingCategories();

			if (!_categories.Any() && this.UseFallBackProvider) {
				FallBackProvider.FillCategories();
				_categories = this.TryFillingCategories();
			}

			return _categories;
		}
	}
}
